layui.use('laydate', function () {
    var laydate = layui.laydate;
    laydate.render({
        elem: '#timestart'
        , type: 'datetime'
    });

    laydate.render({
        elem: '#timeend'
        , type: 'datetime'
    });

    laydate.render({
        elem: '#timestartPackage'
        , type: 'datetime'
    });

    laydate.render({
        elem: '#timeendPackage'
        , type: 'datetime'
    });
    laydate.render({
        elem: '#upStartTime', type: 'datetime'
    });

    laydate.render({
        elem: '#upEndTime', type: 'datetime'
    });


})

$(function () {
    /* $('#pcate').searchableSelect();
    $('#ccate ').searchableSelect(); */
    $('#supplierId').searchableSelect();
    $('#liansuoid').searchableSelect();

    var isziti = $("input[name='isziti']:checked").val();
    if (isziti == 1) {
        $("#ziti").css("display", "block");
    } else {
        $("#ziti").css("display", "none");
    }

    var istangshi = $("input[name='istangshi']:checked").val();
    if (istangshi == 1) {
        $("#tangshi").css("display", "block");
        $("#discount1").css("display", "block");
        $("#discount2").css("display", "block");
    } else {
        $("#tangshi").css("display", "none");
    }

    var iswaimai = $("input[name='iswaimai']:checked").val();
    if (iswaimai == 1) {
        $("#waimai").css("display", "block");
    } else {
        $("#waimai").css("display", "none");
    }

    var istime = $("input[name='istime']:checked").val();
    if (istime == 1) {
        $("#istime").css("display", "none");
    } else {
        $("#istime").css("display", "block");
    }

    var iszitiPackage = $("input[name='iszitiPackage']:checked").val();
    if (iszitiPackage == 1) {
        $("#zitiPackage").css("display", "block");
    } else {
        $("#zitiPackage").css("display", "none");
    }

    var istangshiPackage = $("input[name='istangshiPackage']:checked").val();
    if (istangshiPackage == 1) {
        $("#tangshiPackage").css("display", "block");
        $("#discount1Package").css("display", "block");
        $("#discount2Package").css("display", "block");
    } else {
        $("#tangshiPackage").css("display", "none");
    }

    var iswaimaiPackage = $("input[name='iswaimaiPackage']:checked").val();
    if (iswaimaiPackage == 1) {
        $("#waimaiPackage").css("display", "block");
    } else {
        $("#waimaiPackage").css("display", "none");
    }

    var istimePackage = $("input[name='istimePackage']:checked").val();
    if (istimePackage == 1) {
        $("#istimePackage").css("display", "none");
    } else {
        $("#istimePackage").css("display", "block");
    }

});

function show_type(flag) {
    // if (flag == 0) {
    //     document.getElementById("sendprice").disabled = true;
    //     document.getElementById("dispatchid").disabled = true;
    //
    // } else if (flag == 1) {
    //     document.getElementById("dispatchid").disabled = true;
    //     document.getElementById("sendprice").disabled = false;
    // } else if (flag == 2) {
    //     document.getElementById("sendprice").disabled = true;
    //     document.getElementById("dispatchid").disabled = false;
    // }
}

// $(function () {
//     var x = document.getElementById("free_shipping").value;
//     show_type(x);
//     $(':radio[name=free_shipping]').click(function () {
//         var val = $(this).val();
//         show_type(val);
//     })
// });

$(function () {
    $("#hasoption").click(function () {
        var obj = $(this);
        if (obj.get(0).checked) {
            $("#tboption").show();
        } else {
            $("#tboption").hide();
        }
    });
})

//初始化规格
$(function () {
    var id = $('#id').val();
    $.ajax({
        url: '/product/centre/detail?id=' + id,
        contentType: "application/json",
        dataType: "json",
        type: 'GET',
        success: function (result) {
            if (result.productPackageFlag == 0) {
                $("#danpinShow").show()
                $("#taocanShow").hide()
                $('#danPin').addClass("in active");
                $('#danpinShow').addClass("active");
            } else if (result.productPackageFlag == 1) {
                $("#danpinShow").hide()
                $("#taocanShow").show()
                $('#taoCan').addClass("in active");
                $('#taocanShow').addClass("active");
            }

            $('input[name="timestart"]').val(result.timestart);
            $('input[name="timeend"]').val(result.timeend);

            $('input[name="timestartPackage"]').val(result.timestart);
            $('input[name="timeendPackage"]').val(result.timeend);

            $('input[name="upStartTime"]').val(result.upStartTime);
            $('input[name="upEndTime"]').val(result.upEndTime);
            $('input[name="manudate"]').val(result.manudate);
            $("#areas").html(result.areas);

            $(":radio[name='status'][value='" + result.status + "']").prop("checked", "checked");
            if (result.status == 2) {
                $('#shangjiadiv').css('display', '');
            }
            $(":radio[name='isgongyi'][value='" + result.isgongyi + "']").prop("checked", "checked");
            if (result.isgongyi == 1) {
                $('#gongyidiv').css('display', '');
            }
            $(":radio[name='showsupply'][value='" + result.showsupply + "']").prop("checked", "checked");
            $(":radio[name='uncancelable'][value='" + result.uncancelable + "']").prop("checked", "checked");

            show_type(result.freeShipping);
            if (result.freeShipping == 1) {
                $("#sendprice").val(result.sendprice);
            }

            if (result.productId != null && result.productId != '') {
                // $("#productprice").attr("readonly", true);
                // $("#costprice").attr("readonly", true);
                // $("#title").attr("readonly", true);
                // $("#shortTitle").attr("readonly", true);
                // $("#goodscode").attr("readonly", true);
                // $("#ccate").attr("readonly", true);
                // $("#pcate").attr("readonly", true);
                // $("#supplierId").attr("readonly", true);
                // $("#unit").attr("readonly", true);
                // $("#selfvalue").attr("readonly", true);
                // $("#timestart").attr("readonly", true);
                // $("#timeend").attr("readonly", true);
                // $("#thumb").attr("readonly", true);
                // $("#thumbSquare").attr("readonly", true);
                // $("#thumbUrlBak").attr("readonly", true);
                // $(".btn-file").attr('disabled', true);
                // $("#pcate").attr("disabled", "disabled").css("background-color", "#EEEEEE;");
                // $("#ccate").attr("disabled", "disabled").css("background-color", "#EEEEEE;");
                // $("#supplierId").attr("disabled", "disabled").css("background-color", "#EEEEEE;");
                // $("#weight").attr("readonly", true);
                // $("#sales").attr("readonly", true);
                // $("#viewcount").attr("readonly", true);
                // $("#credit").attr("readonly", true);
                // $("input[name='isgongyi']").attr("disabled", true);
                // $("input[name='showsupply']").attr("disabled", true);
                // $("input[name='showsupply']").attr("disabled", true);
                $("input[name='uncancelable']").attr("disabled", true);
                $("#content").attr("disabled", true).css("cursor", "default");
                // $("#guarantday").attr("readonly", true);

            }

            //初始化单品
            if (result.productPackageFlag == 1) {
                if (result.productPackageSkuList) {
                    for (var i = 0; i < result.productPackageSkuList.length; i++) {
                        addPackage();

                        // //给商品选择框赋值
                        $("#packageThumb" + packageNum).attr("src", result.productPackageSkuList[i].productCentreThumb);
                        $("#productName" + packageNum).html(result.productPackageSkuList[i].productCentreTitle);
                        if (result.productPackageSkuList[i].skuId) {
                            $("#spec" + packageNum).html(result.productPackageSkuList[i].title);
                            $("#inventory" + packageNum).html(result.productPackageSkuList[i].stock);
                        } else {
                            $("#spec" + packageNum).html("无");
                            $("#inventory" + packageNum).html(result.total);
                        }
                        //存储选择的套餐内商品
                        packageSkuData[packageNum + ""] = {
                            id: result.productPackageSkuList[i].id,
                            refProductCentreId: result.productPackageSkuList[i].refProductCentreId,
                            centreId: result.productPackageSkuList[i].centreId,
                            skuId: result.productPackageSkuList[i].skuId,
                            title: result.productPackageSkuList[i].title,
                            thumb: result.productPackageSkuList[i].thumb,
                            specs: result.productPackageSkuList[i].specs,
                            stock: result.productPackageSkuList[i].stock,
                        }
                    }
                }
            }


            var productType = result.productType;
            var isziti = result.isziti;
            var istangshi = result.istangshi;
            var iswaimai = result.iswaimai;

            if (result.hasoptionsbuy == 1) {
                $('input[name="hasoption"]').attr('checked', true);
            } else if (result.hasoption == 1 && result.hasoptionsbuy == 0) {
                $('input[name="hasoption"]').attr('checked', true);
            }
            if (result.specList != null && result.specList.length > 0) {
                var html = '';

                for (var i = 0; i < result.specList.length; i++) {
                    html += '<div class="panel panel-default spec_item" id="spec_dcx' + specCountNum + '">' +
                        '<div class="panel-body"> ' +
                        '<input type="hidden" class="form-control spec_id" value="' + result.specList[i].id + '" /> ' +
                        '<div class="form-group"> ' +
                        '<label class="col-xs-12 col-sm-3 col-md-2 control-label">规格名 </label> ' +
                        '<div class="col-sm-9 col-xs-12"> ' +
                        '<input name="spec_title[dcx' + specCountNum + ']" type="text" class="form-control spec_title" value="' + result.specList[i].title + '" placeholder="(比如: 颜色)" /> ' +
                        '</div> ' +
                        '</div> ';
                    if (result.hasoptionsbuy == 1) {
                        html += '<div name="listspecdel" style=""> ' +
                            '<div class="form-group"> ' +
                            '<label class="col-xs-12 col-sm-3 col-md-2 control-label"></label> ' +
                            '<div class="col-sm-9 col-xs-12"> ' +
                            '<a href="javascript:void(0);" class="btn btn-danger" onclick="removeSpec(\'dcx' + specCountNum + '\')"> <i class="fa fa-plus"></i> 删除规格</a> ' +
                            '</div> ' +
                            '</div> ' +
                            '</div> ';
                    } else {
                        html += '<div name="listspec" style=""> ' +
                            '<div class="form-group"> ' +
                            '<label class="col-xs-12 col-sm-3 col-md-2 control-label">规格项</label> ' +
                            '<div class="col-sm-9 col-xs-12"> ' +
                            '<div id="spec_item_dcx' + specCountNum + '" class="spec_item_items">';
                        if (result.specList[i].specItemList != null && result.specList[i].specItemList.length > 0) {
                            for (var j = 0; j < result.specList[i].specItemList.length; j++) {
                                html += '<div class="spec_item_item" style="float:left;margin:0 5px 10px 0;width:250px;">' +
                                    '<div class="input-group" style="margin:10px 0;">' +
                                    // '<span class="input-group-addon"> <label class="checkbox-inline" style="margin-top:-20px;"><input type="checkbox" checked="" value="1" onclick="showItem(this)" /></label></span> ' +
                                    '<input placeholder="*请勿使用+号" data-index-oldId="'+ result.specList[i].specItemList[j].id +'" data-index="' + specItemHiddenId + '" type="text" class="form-control spec_item_title error" value="' + result.specList[i].specItemList[j].title + '" /> ' +
                                    '<span class="input-group-addon"><a href="javascript:;" onclick="removeSpecItem(this)" title="删除"> <i class="fa fa-times"></i></a></span> ' +
                                    '</div>' +
                                    '<div class="input-group "> ' +
                                    '*如填写将加价<input type="text" style="width: 80px;" class="form-control spec_item_price error" value="' + result.specList[i].specItemList[j].price + '" /> ' +
                                    '<input type="text" value="' + result.specList[i].specItemList[j].thumb + '" class="form-control thumb" autocomplete="off" id="specItemThumb_' + result.specList[i].specItemList[j].id + '"/> ' +
                                    '<span class="input-group-btn"> <button class="btn btn-sm btn-default" type="button" onclick="onSelectImgBtnClick(\'specItemThumb_' + result.specList[i].specItemList[j].id + '\',\'dd\');">选择图片</button> </span> ' +
                                    '</div> ' +
                                    '<div class="input-group " style="margin-top:.5em;"> ' +
                                    //'<em class="close" style="position:absolute; top: 0px; right: -14px;" title="删除这张图片" onclick="deleteImage(this)">×</em> '+
                                    '</div></div>';
                                specItemHiddenId = specItemHiddenId+1;
                            }
                        }
                        html += '</div> ' +
                            '</div> ' +
                            '</div> ' +
                            '<div class="form-group"> ' +
                            '<label class="col-xs-12 col-sm-3 col-md-2 control-label"></label> ' +
                            '<div class="col-sm-9 col-xs-12"> ' +
                            '<span> <a id="add-specitem-dcx' + specCountNum + '" specid="dcx' + specCountNum + '" class="btn btn-info add-specitem" onclick="addSpecItem(\'dcx' + specCountNum + '\')"> ' +
                            '<i class="fa fa-plus"></i> 添加规格项</a></span> ' +
                            '<a class="btn btn-danger" onclick="removeSpec(\'dcx' + specCountNum + '\')"> <i class="fa fa-plus"></i> 删除规格</a> ' +
                            '</div> ' +
                            '</div> ' +
                            '</div> ';

                    }
                    html += '</div></div>';
                    specCountNum++;
                }
                $('#specs').append(html);
                $('#tboption').css('display', 'block');
            }

            var skus = [];
            if (result.skuList.length > 0) {
                for (var i = 0; i < result.skuList.length; i++) {
                    var sku = {
                        id: result.skuList[i].id,
                        title: result.skuList[i].title,
                        costprice: result.skuList[i].costprice,
                        vipprice: result.skuList[i].vipprice,
                        zitiprice: result.skuList[i].zitiprice,
                        tangshiprice: result.skuList[i].tangshiprice,
                        waimaiprice: result.skuList[i].waimaiprice,
                        tangshivipprice: result.skuList[i].tangshivipprice,
                        waimaivipprice: result.skuList[i].waimaivipprice,
                        zitivipprice: result.skuList[i].zitivipprice,
                        headcommission: result.skuList[i].headcommission,
                        headtype: result.skuList[i].headtype,
                        marketprice: result.skuList[i].marketprice,
                        productprice: result.skuList[i].productprice,
                        stock: result.skuList[i].stock,
                        salesreal: result.skuList[i].salesreal,
                        superiorcommission: result.skuList[i].superiorcommission,
                        superiortype: result.skuList[i].superiortype,
                        weight: result.skuList[i].weight,
                        specs: result.skuList[i].specs
                    }
                    skus.push(sku);
                }
                var len = skus.length;
                var h = new Array(len);
                if (result.hasoptionsbuy == 1) {
                    var hh = '<input name="kw" type="hidden"  value="1"/>';

                    for (var i = 0; i < len; i++) {
                        var html = '<table class="table table-bordered table-condensed skuTable"><thead><tr class="active">';
                        html += "<th style='width:80px;'></th>";

                        html += '<th class="info" style="width:130px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">编号</div><div class="input-group"><input type="text" class="form-control option_id_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';

                        html += '<th class="info" style="width:130px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">库存</div><div class="input-group"><input type="text" class="form-control option_stock_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_stock\');"></a></span></div></div></th>';

                        html += '<th class="info" style="width:130px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">销量</div><div class="input-group"><input type="text" class="form-control option_salesreal_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';


                        if (productType == 6) {
                            if (isziti == 1) {
                                html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">自提价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
                                html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">自提vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
                            }
                            if (istangshi == 1) {
                                html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">堂食价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
                                html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">堂食vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
                            }
                            if (iswaimai == 1) {
                                html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">外卖价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
                                html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">外卖vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
                            }
                        } else {
                            html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">销售价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
                            html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">市场价格</div><div class="input-group"><input type="text" class="form-control option_productprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_productprice\');"></a></span></div></div></th>';
                            html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
                        }

                        html += '<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">重量（克）</div><div class="input-group"><input type="text" class="form-control option_weight_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_weight\');"></a></span></div></div></th>';
                        html += '<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">门店佣金（元）</div><div class="input-group"><input type="text" class="form-control option_headcommission_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_headcommission\');"></a></span></div></div></th>';
                        html += '<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">门店推荐人佣金（元）</div><div class="input-group"><input type="text" class="form-control option_superiorcommission_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_superiorcommission\');"></a></span></div></div></th>';
                        html += '</tr></thead>';
                        hh += "<tr>";

                        hh += "<td style='width:80px;'>" + skus[i].title + "</td>";

                        hh += '<td class="info"><input readonly="readonly" type="text" class="form-control option_id option_id_' + (skus[i].specs) + '" value="' + (skus[i].id) + '"/></td>';
                        hh += '<td class="info"><input type="number" min="0" class="form-control option_stock" value="' + (skus[i].stock) + '"/></td>';
                        hh += '<td class="info"><input readonly="readonly" type="text" class="form-control option_salesreal" value="' + (skus[i].salesreal) + '"/></td>';

                        //hh += '<input type="hidden" class="form-control option_id" value="' + skus[i].id + '"/>';
                        /* hh += '<input type="hidden" class="form-control option_ids" value="' + skus[i].id + '"/>'; */
                        hh += '<input type="hidden" class="form-control option_title" value="' + skus[i].title + '"/></td>';
                        /* hh += '<input name="option_virtual_' + skus[i].id + '[]"type="hidden" class="form-control option_title option_title_' + skus[i].id + '" value="' + (val.virtual == 'undefined' ? '': val.virtual) + '"/></td>'; */
                        hh += '</td>';

                        if (productType == 6) {
                            if (isziti == 1) {
                                hh += '<td class="success"><input readonly="readonly" name="option_marketprice_' + skus[i].id + '[]" type="number" min="0" class="form-control option_zitiprice option_marketprice_' + skus[i].id + '" value="' + (skus[i].zitiprice == 'undefined' ? '' : skus[i].zitiprice) + '"/></td>';
                                hh += '<td class="warning"><input name="option_vipprice_' + skus[i].id + '[]" type="number" min="0" class="form-control option_zitivipprice option_vipprice_' + skus[i].id + '" " value="' + (skus[i].zitivipprice == 'undefined' ? '' : skus[i].zitivipprice) + '"/></td>';
                            }
                            if (istangshi == 1) {
                                hh += '<td class="success"><input readonly="readonly" name="option_marketprice_' + skus[i].id + '[]" type="number" min="0" class="form-control option_tangshiprice option_marketprice_' + skus[i].id + '" value="' + (skus[i].tangshiprice == 'undefined' ? '' : skus[i].tangshiprice) + '"/></td>';
                                hh += '<td class="warning"><input name="option_vipprice_' + skus[i].id + '[]" type="number" min="0" class="form-control option_tangshivipprice option_vipprice_' + skus[i].id + '" " value="' + (skus[i].tangshivipprice == 'undefined' ? '' : skus[i].tangshivipprice) + '"/></td>';
                            }
                            if (iswaimai == 1) {
                                hh += '<td class="success"><input readonly="readonly" name="option_marketprice_' + skus[i].id + '[]" type="number" min="0" class="form-control option_waimaiprice option_marketprice_' + skus[i].id + '" value="' + (skus[i].waimaiprice == 'undefined' ? '' : skus[i].waimaiprice) + '"/></td>';
                                hh += '<td class="warning"><input name="option_vipprice_' + skus[i].id + '[]" type="number" min="0" class="form-control option_waimaivipprice option_vipprice_' + skus[i].id + '" " value="' + (skus[i].waimaivipprice == 'undefined' ? '' : skus[i].waimaivipprice) + '"/></td>';
                            }
                        } else {
                            hh += '<td class="success"><input name="option_marketprice_' + skus[i].id + '[]" type="number" min="0" class="form-control option_marketprice option_marketprice_' + skus[i].id + '" value="' + (skus[i].marketprice) + '"/></td>';
                            hh += '<td class="warning"><input name="option_productprice_' + skus[i].id + '[]" type="number" min="0" class="form-control option_productprice option_productprice_' + skus[i].id + '" " value="' + (skus[i].productprice) + '"/></td>';
                            hh += '<td class="warning"><input name="option_vipprice_' + skus[i].id + '[]" type="number" min="0" class="form-control option_vipprice option_vipprice_' + skus[i].id + '" " value="' + (skus[i].vipprice) + '"/></td>';
                        }

                        hh += '<td class="info"><input name="option_weight_' + skus[i].id + '[]" type="number" min="0" class="form-control option_weight option_weight_' + skus[i].id + '" " value="' + (skus[i].weight) + '"/></td>';
                        //hh += '<td class="info"><input name="option_headcommission_' + skus[i].id  +'[]" type="text" class="form-control option_headcommission option_headcommission_' + skus[i].id  +'" " value="' +(val.headcommission=='undefined'?'':val.headcommission )+'"/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_superiorcommission\');"></a></span></td>';
                        hh += '<td class="info" style="width:150px;"><div class=""><div class="input-group"><input name="option_headcommission_' + skus[i].id + '[]" type="number" min="0" class="form-control option_headcommission option_headcommission_' + skus[i].id + '" " value="' + (skus[i].headcommission) + '"/><span class="input-group-addon" style="padding:0px;"><select  name="option_headtype_' + skus[i].id + '[]" class="option_headtype option_headtype_' + skus[i].id + '"  style="border-style:solid; border-color:#FFF">';
                        if (skus[i].headtype == 0) {
                            hh += '<option value="0" selected>元</option><option value="1">%</option></select></span></div></div></td>';
                        } else {
                            hh += '<option value="0">元</option><option value="1" selected>%</option></select></span></div></div></td>';
                        }
                        hh += '<td class="info" style="width:150px;"><div class=""><div class="input-group"><input name="option_superiorcommission_' + skus[i].id + '[]" type="number" min="0" class="form-control option_superiorcommission option_superiorcommission_' + skus[i].id + '" " value="' + (skus[i].superiorcommission) + '"/><span class="input-group-addon" style="padding:0px;"><select name="option_superiortype_' + skus[i].id + '[]" class="option_superiortype option_superiortype_' + skus[i].id + '"  style="border-style:solid; border-color:#FFF">';
                        if (sku[i].superiortype == 0) {
                            hh += '<option value="0" selected>元</option><option value="1">%</option></select></span></div></div></td>';
                        } else {
                            hh += '<option value="0">元</option><option value="1" selected>%</option></select></span></div></div></td>';
                        }
                        hh += "</tr>";
                    }
                    html += hh;
                    html += "</table>";
                    $("#options").html(html);
                } else {
                    var html = '<table class="table table-bordered table-condensed skuTable"><thead><tr class="active">';
                    var specs = result.specList;
                    var skuList = result.skuList;

                    specs.sort(function (x, y) {
                        if (x.specItemList.length > y.specItemList.length) {
                            return 1;
                        }
                        if (x.specItemList.length < y.specItemList.length) {
                            return -1;
                        }
                    });

                    var len = specs.length;
                    var newlen = 1;
                    var skuListLength = skuList.length;
                    var h = new Array(len);
                    var rowspans = new Array(len);
                    for (var i = 0; i < len; i++) {
                        html += "<th style='width:80px;'>" + specs[i].title + "</th>";
                    }
                    html += '<th class="info" style="width:130px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">编号</div><div class="input-group"><input type="text" class="form-control option_id_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';

                    html += '<th class="info" style="width:130px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">库存</div><div class="input-group"><input type="text" class="form-control option_stock_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_stock\');"></a></span></div></div></th>';

                    html += '<th class="info" style="width:130px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">销量</div><div class="input-group"><input type="text" class="form-control option_salesreal_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';

                    if (productType == 6) {
                        if (isziti == 1) {
                            html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">自提价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
                            html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">自提vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
                        }
                        if (istangshi == 1) {
                            html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">堂食价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
                            html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">堂食vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
                        }
                        if (iswaimai == 1) {
                            html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">外卖价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
                            html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">外卖vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
                        }
                    } else {
                        html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">销售价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
                        html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">市场价格</div><div class="input-group"><input type="text" class="form-control option_productprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_productprice\');"></a></span></div></div></th>';
                        html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
                    }

                    html += '<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">重量（克）</div><div class="input-group"><input type="text" class="form-control option_weight_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_weight\');"></a></span></div></div></th>';
                    html += '<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">门店佣金（元）</div><div class="input-group"><input type="text" class="form-control option_headcommission_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_headcommission\');"></a></span></div></div></th>';
                    html += '<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">门店推荐人佣金（元）</div><div class="input-group"><input type="text" class="form-control option_superiorcommission_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_superiorcommission\');"></a></span></div></div></th>';
                    html += '</tr></thead>';

                    var hh = '';
                    for (var i = 0; i < skuListLength; i++) {

                        var skuTitle = skuList[i].title;
                        hh += "<tr>";

                        var skuTitleArray = skuTitle.split("+");
                        for (var j = 0; j < skuTitleArray.length; j++) {
                            hh += "<td>" + skuTitleArray[j] + "</td>";
                        }

                        hh += '<td class="info"><input readonly="readonly" type="text" class="form-control option_id option_id_' + (skus[i].specs) + '" value="' + (skuList[i].id) + '"/></td>';
                        hh += '<td class="info"><input type="number" min="0" class="form-control option_stock" value="' + (skuList[i].stock) + '"/></td>';
                        hh += '<td class="info"><input readonly="readonly" type="text" class="form-control option_salesreal" value="' + (skuList[i].salesreal) + '"/></td>';

                        // hh += '<input type="hidden" class="form-control option_id" value="' + skuList[i].id + '"/>';
                        hh += '<input type="hidden" class="form-control option_ids" value="' + skuList[i].specs + '"/>';
                        hh += '<input type="hidden" class="form-control option_title" value="' + skuList[i].title + '"/>';
                        hh += '<input type="hidden" class="form-control option_specItemHiddenId" value="' + skuList[i].specs + '"/></td>';

                        if (productType == 6) {
                            if (isziti == 1) {
                                hh += '<td class="success"><input type="number" min="0" class="form-control option_zitiprice" value="' + (skuList[i].zitiprice == 'undefined' ? '' : skuList[i].zitiprice) + '"/></td>';
                                hh += '<td class="warning"><input type="number" min="0" class="form-control option_zitivipprice" " value="' + (skuList[i].zitivipprice == 'undefined' ? '' : skuList[i].zitivipprice) + '"/></td>';
                            }
                            if (istangshi == 1) {
                                hh += '<td class="success"><input type="number" min="0" class="form-control option_tangshiprice" value="' + (skuList[i].tangshiprice == 'undefined' ? '' : skuList[i].tangshiprice) + '"/></td>';
                                hh += '<td class="warning"><input type="number" min="0" class="form-control option_tangshivipprice" value="' + (skuList[i].tangshivipprice == 'undefined' ? '' : skuList[i].tangshivipprice) + '"/></td>';
                            }
                            if (iswaimai == 1) {
                                hh += '<td class="success"><input type="number" min="0" class="form-control option_waimaiprice" value="' + (skuList[i].waimaiprice == 'undefined' ? '' : skuList[i].waimaiprice) + '"/></td>';
                                hh += '<td class="warning"><input type="number" min="0" class="form-control option_waimaivipprice" " value="' + (skuList[i].waimaivipprice == 'undefined' ? '' : skuList[i].waimaivipprice) + '"/></td>';
                            }
                        } else {
                            hh += '<td class="success"><input type="number" min="0" class="form-control option_marketprice" value="' + skuList[i].marketprice + '"/></td>';
                            hh += '<td class="warning"><input type="number" min="0" class="form-control option_productprice" value="' + skuList[i].productprice + '"/></td>';
                            hh += '<td class="warning"><input type="number" min="0" class="form-control option_vipprice" value="' + skuList[i].vipprice + '"/></td>';
                        }

                        hh += '<td class="info"><input type="number" min="0" class="form-control option_weight"  value="' + skuList[i].weight + '"/></td>';
                        hh += '<td class="info" style="width:150px;"><div class=""><div class="input-group"><input type="number" min="0" class="form-control option_headcommission" value="' + skuList[i].headcommission + '"/><span class="input-group-addon" style="padding:0px;"><select type="text" class="option_headtype"  style="border-style:solid; border-color:#FFF"  >'
                        if (skuList[i].headtype == 0) {
                            hh += '<option value="0" selected>元</option><option value="1">%</option></select></span></div></div></td>';
                        } else {
                            hh += '<option value="0">元</option><option value="1" selected>%</option></select></span></div></div></td>';
                        }
                        hh += '<td class="info" style="width:150px;"><div class=""><div class="input-group"><input type="number" min="0" class="form-control option_superiorcommission" value="' + skuList[i].superiorcommission + '"/><span class="input-group-addon" style="padding:0px;"><select type="text" class="option_superiortype"  style="border-style:solid; border-color:#FFF"  >';

                        if (skuList[i].superiortype == 0) {
                            hh += '<option value="0" selected>元</option><option value="1">%</option></select></span></div></div></td>';
                        } else {
                            hh += '<option value="0">元</option><option value="1" selected>%</option></select></span></div></div></td>';
                        }

                        hh += "</tr>";
                    }
                    html += hh;
                    html += "</table>";
                    $("#options").html(html);
                }
            }
        }
    })

    var checkIsCentre = $("#checkIsCentre").val();
    if (checkIsCentre == 0) {

    }
    //修改佣金设置
    // if ($('#is_fx_commission').is(':checked')) {
    //     document.getElementById("superiorcommission").disabled = false;
    //     document.getElementById("headcommission").disabled = false;
    //     // document.getElementById("usercommission").disabled = false;
    //     // document.getElementById("superusercommission").disabled = false;
    // } else {
    //     document.getElementById("superiorcommission").disabled = true;
    //     document.getElementById("headcommission").disabled = true;
    //     // document.getElementById("usercommission").disabled = true;
    //     // document.getElementById("superusercommission").disabled = true;
    // }
})


/**
 * 加载图片URL
 * @param inputId
 * @param imgId
 * @param url
 */
function loadImgUrl(inputId, imgId, url) {
    $('#' + inputId + '').val(url);
    $('#' + imgId + '').attr('src', url);
}

// 批量上传图片
function selectImgs(domId) {
    layer.open({
        id: 'selectImgs',
        type: 2,
        title: '批量选择图片',
        maxmin: true,
        shadeClose: false,
        area: ['60%', '70%'],
        content: '/platform/config/batchUploadImg/' + domId // iframe的url
    });
}

function loadImgsInfo(domId, result) {
    if (!result || result.length < 1) {
        parent.layer.msg("上传图片失败!", {icon: 7});
        return;
    }
    $('#thumbUrl').val(result.join(","));
}

// 加载图片进ueditor中
function loadImgsToUeditor(result) {
    if (!result || result.length < 1) {
        parent.layer.msg("上传图片失败!", {icon: 7});
        return;
    }
    console.info(result);
    /* var imgUrlArray = result.split(","); */
    let editor = UE.getEditor('content');
    for (var i = 0; i < result.length; i++) {
        var imgUrl = result[i];
        editor.execCommand('inserthtml', `<img src=${imgUrl}>`);
    }
}

function renderCategoryType(obj) {
    var index = obj.options[obj.selectedIndex].value;
    var html = "<option value='0'>请选择顶级分类</option>";
    if (index == 0) {
        $("#pcate").html(html);
    } else {
        $.ajax({
            url: "/category/manage/getCategorysByType",
            data: {"type": index},
            dataType: "json",
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    html += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
                }
                $("#pcate").html(html);
            }
        })
    }
}

function radioIsChecked() {
    if ($("#istime2").is(':checked')) {
        $('#istime').show();
    } else {
        $('#istime').hide();
    }
}

function iszitiChange() {
    var isziti = $("input[name='isziti']:checked").val();
    if (isziti == 1) {
        $("#ziti").css("display", "block");
    } else {
        $("#ziti").css("display", "none");
        $("#zitiprice").val("")
        $("#zitivipprice").val("")
    }
}

function istangshiChange() {
    var istangshi = $("input[name='istangshi']:checked").val();
    if (istangshi == 1) {
        $("#tangshi").css("display", "block");
        $("#discount1").css("display", "block");
        $("#discount2").css("display", "block");
    } else {
        $("#discount1").css("display", "none");
        $("#discount2").css("display", "none");
        $("#tangshi").css("display", "none");
        $("#tangshiprice").val("")
        $("#tangshivipprice").val("")
        $("input[name='discountStatus']:checked").prop("checked", false);
        $('input:radio[name=discountStatus]')[1].checked = true;
        $("#discount").val("")
    }
}

function iswaimaiChange() {
    var iswaimai = $("input[name='iswaimai']:checked").val();
    if (iswaimai == 1) {
        $("#waimai").css("display", "block");
    } else {
        $("#waimai").css("display", "none");
        $("#waimaiproductprice").val("")
        $("#waimaiprice").val("")
        $("#waimaivipprice").val("")
    }
}

function toCategoryOne() {
    // iframe层
    layer.open({
        id: 'group_add',
        type: 2,
        title: '选择顶级分类',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['90%', '90%'],
        content: '/category/manage/toCategory?idDom=pcate&nameDom=pcateName&singleSelect=1&callback=pcateCallback&count=1' // iframe的url
    });
}

function toCategoryTwo() {
    var parentid = $("#pcate").val();
    if (!parentid) {
        layer.msg("请选择顶级分类");
        return;
    }
    // iframe层
    layer.open({
        id: 'group_add',
        type: 2,
        title: '选择下级分类',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['90%', '90%'],
        content: '/category/manage/toCategory?idDom=ccate&nameDom=ccateName&singleSelect=1&callback=pcateCallback&count=2&parentid=' + parentid // iframe的url
    });
}

function pcateCallback(obj) {
    $("#" + obj.nameDom).val(obj.nameStrs);
    $("#" + obj.idDom).val(obj.idStrs);
    if (obj.count == 1) {
        $("#ccate").val("");
        $("#ccateName").val("");
    }
}

function categoryCloseClick(event) {
    if (event == 'one') { // 一级分类清空
        $("#pcateName").val('')
        $("#pcate").val('')
        $("#ccateName").val('')
        $("#ccate").val('')
    } else { // 二级分类清空
        $("#ccateName").val('')
        $("#ccate").val('')

    }
}

function onSelectImgBtnClick(inputId, imgId) {
    layer.open({
        id: 'selectImg',
        type: 2,
        title: '选择图片',
        maxmin: true,
        shadeClose: false,
        area: ['60%', '70%'],
        content: '/platform/config/selectImg/' + inputId + "/" + imgId // iframe的url
    });
}

var specCountNum = 1;

function addSpec() {
    var html = '<div class="panel panel-default spec_item" id="spec_dcx' + specCountNum + '">' +
        '<div class="panel-body"> ' +
        '<input name="spec_id[]" type="hidden" class="form-control spec_id" value="dcx' + specCountNum + '" /> ' +
        '<div class="form-group"> ' +
        '<label class="col-xs-12 col-sm-3 col-md-2 control-label">规格名 </label> ' +
        '<div class="col-sm-9 col-xs-12"> ' +
        '<input name="spec_title[dcx' + specCountNum + ']" type="text" class="form-control spec_title" value="" placeholder="(比如: 颜色)" /> ' +
        '</div> ' +
        '</div> ';

    var secondHtml = '';

    secondHtml = '<div name="listspec" style=""> ' +
        '<div class="form-group"> ' +
        '<label class="col-xs-12 col-sm-3 col-md-2 control-label">规格项</label> ' +
        '<div class="col-sm-9 col-xs-12"> ' +
        '<div id="spec_item_dcx' + specCountNum + '" class="spec_item_items"></div> ' +
        '</div> ' +
        '</div> ' +
        '<div class="form-group"> ' +
        '<label class="col-xs-12 col-sm-3 col-md-2 control-label"></label> ' +
        '<div class="col-sm-9 col-xs-12"> ' +
        '<span> <a id="add-specitem-dcx' + specCountNum + '" specid="dcx' + specCountNum + '" class="btn btn-info add-specitem" onclick="addSpecItem(\'dcx' + specCountNum + '\')"> ' +
        '<i class="fa fa-plus"></i> 添加规格项</a></span> ' +
        '<a class="btn btn-danger" onclick="removeSpec(\'dcx' + specCountNum + '\')"> <i class="fa fa-plus"></i> 删除规格</a> ' +
        '</div> ' +
        '</div> ' +
        '</div> ' +
        '<div name="listspecdel" style="display:none"> ' +
        '<div class="form-group"> ' +
        '<label class="col-xs-12 col-sm-3 col-md-2 control-label"></label> ' +
        '<div class="col-sm-9 col-xs-12"> ' +
        '<a href="javascript:void(0);" class="btn btn-danger" onclick="removeSpec(\'dcx' + specCountNum + '\')"> <i class="fa fa-plus"></i> 删除规格</a> ' +
        '</div> ' +
        '</div> ' +
        '</div> ';

    html += secondHtml + '</div></div>';


    var len = $(".spec_item").length;

    $("#add-spec").html("正在处理...").attr("disabled", "true").toggleClass("btn-primary");
    $("#add-spec").html('<i class="fa fa-plus"></i> 添加规格').removeAttr("disabled").toggleClass("btn-primary");
    $('#specs').append(html);
    var len = $(".add-specitem").length - 1;
    $(".add-specitem:eq(" + len + ")").focus();
    optionchanged = true;

    specCountNum++;
}

var specItemHiddenId = 1;

function addSpecItem(specid) {
    var html = '<div class="spec_item_item" style="float:left;margin:0 5px 10px 0;width:250px;">' +
        '<div class="input-group" style="margin:10px 0;">' +
        // '<span class="input-group-addon"> <label class="checkbox-inline" style="margin-top:-20px;"><input type="checkbox" checked="" value="1" onclick="showItem(this)" /></label></span> ' +
        '<input placeholder="*请勿使用+号" data-index=' + specItemHiddenId + ' type="text" class="form-control spec_item_title error" name="spec_item_title_[]" value="" /> ' +
        '<span class="input-group-addon"><a href="javascript:;" onclick="removeSpecItem(this)" title="删除"> <i class="fa fa-times"></i></a></span> ' +
        '</div>' +
        '<div class="input-group " style="margin:10px 0;"> ' +
        '*如填写将加价<input data-index="' + specItemHiddenId + '" type="text" style="width: 80px;" class="form-control spec_item_price error" value="0" /> ' +
        '</div><div class="input-group "> ' +
        '<input type="text" value="" class="form-control thumb" id="specItemThumb_' + specItemHiddenId + '" autocomplete="off" /> ' +
        '<span class="input-group-btn"> <button class="btn btn-sm btn-default" style="padding:7px 10px" type="button" onclick="onSelectImgBtnClick(\'specItemThumb_' + specItemHiddenId + '\',\'dd\');">选择图片</button> </span> ' +
        '</div> ' +
        '<div class="input-group " style="margin-top:.5em;"> ' +
        //'<em class="close" style="position:absolute; top: 0px; right: -14px;" title="删除这张图片" onclick="deleteImage(this)">×</em> '+
        '</div>';
    $("#add-specitem-" + specid).html("正在处理...").attr("disabled", "true");
    $("#add-specitem-" + specid).html('<i class="fa fa-plus"></i> 添加规格项').removeAttr("disabled");
    $('#spec_item_' + specid).append(html);
    var len = $("#spec_" + specid + " .spec_item_title").length - 1;
    $("#spec_" + specid + " .spec_item_title:eq(" + len + ")").focus();
    optionchanged = true;
    specItemHiddenId++;
}

function calc() {
    optionchanged = false;
    var html = '<table class="table table-bordered table-condensed skuTable"><thead><tr class="active">';
    var specs = [];
    if ($('.spec_item').length <= 0) {
        $("#options").html('');
        return;
    }
    $(".spec_item").each(function (i) {
        var _this = $(this);

        var spec = {
            id: _this.find(".spec_id").val(),
            title: _this.find(".spec_title").val()
        };

        var items = [];
        _this.find(".spec_item_item").each(function () {
            var __this = $(this);
            var item = {
                //id: __this.find(".spec_item_id").val(),
                id: __this.find(".spec_item_title").attr("data-index"),
                title: __this.find(".spec_item_title").val(),
                virtual: __this.find(".spec_item_virtual").val(),
                specItemHiddesId: __this.find(".spec_item_title").attr("data-index"),
                price: __this.find(".spec_item_price").val()
                /* show: __this.find(".spec_item_show").get(0).checked ? "1": "0" */
            }
            items.push(item);
        });
        spec.items = items;
        specs.push(spec);
    });

    specs.sort(function (x, y) {
        if (x.items.length > y.items.length) {
            return 1;
        }
        if (x.items.length < y.items.length) {
            return -1;
        }
    });

    var len = specs.length; //规格数量
    var newlen = 1; // 所有规格项组合数量
    var h = new Array(len);
    var rowspans = new Array(len);
    for (var i = 0; i < len; i++) {
        html += "<th style='width:80px;'>" + specs[i].title + "</th>";
        var itemlen = specs[i].items.length;
        if (itemlen <= 0) {
            itemlen = 1
        }
        ;
        newlen *= itemlen;
        h[i] = new Array(newlen);
        for (var j = 0; j < newlen; j++) {
            h[i][j] = new Array();
        }
        var l = specs[i].items.length;
        rowspans[i] = 1;
        for (j = i + 1; j < len; j++) {
            rowspans[i] *= specs[j].items.length;
        }
    }

    var productType = $("#productType").val()
    var isziti = $("input[name='isziti']:checked").val();
    var istangshi = $("input[name='istangshi']:checked").val();
    var iswaimai = $("input[name='iswaimai']:checked").val();

    html += '<th class="info" style="width:130px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">库存</div><div class="input-group"><input type="text" class="form-control option_stock_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_stock\');"></a></span></div></div></th>';
    if (productType == 6) {
        if (isziti == 1) {
            html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">自提价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
            html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">自提vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
        }
        if (istangshi == 1) {
            html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">堂食价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
            html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">堂食vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
        }
        if (iswaimai == 1) {
            html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">外卖价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
            html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">外卖vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
        }
    } else {
        html += '<th class="success" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">销售价格</div><div class="input-group"><input readonly="readonly" type="text" class="form-control option_marketprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置"></a></span></div></div></th>';
        html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">市场价格</div><div class="input-group"><input type="text" class="form-control option_productprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_productprice\');"></a></span></div></div></th>';
        html += '<th class="warning" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">vip价格</div><div class="input-group"><input type="text" class="form-control option_vipprice_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_vipprice\');"></a></span></div></div></th>';
    }
    html += '<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">重量（克）</div><div class="input-group"><input type="text" class="form-control option_weight_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_weight\');"></a></span></div></div></th>';
    html += '<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">门店佣金（元）</div><div class="input-group"><input type="text" class="form-control option_headcommission_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_headcommission\');"></a></span></div></div></th>';
    html += '<th class="info" style="width:150px;"><div class=""><div style="padding-bottom:10px;text-align:center;font-size:16px;">门店推荐人佣金（元）</div><div class="input-group"><input type="text" class="form-control option_superiorcommission_all"VALUE=""/><span class="input-group-addon"><a href="javascript:;" class="fa fa-hand-o-down" title="批量设置" onclick="setCol(\'option_superiorcommission\');"></a></span></div></div></th>';
    html += '</tr></thead>';


    for (var m = 0; m < len; m++) {
        var k = 0,
            kid = 0,
            n = 0;
        var specItemPrice = 0;
        for (var j = 0; j < newlen; j++) {
            var rowspan = rowspans[m];

            h[m][j] = {
                title: specs[m].items[kid].title,
                virtual: specs[m].items[kid].virtual,
                // html: "<td rowspan='" + rowspan + "'>" + specs[m].items[kid].title + "</td>\r\n",
                html: "<td>" + specs[m].items[kid].title + "</td>\r\n",
                id: specs[m].items[kid].id,
                specItemHiddesId: specs[m].items[kid].specItemHiddesId,
                price: specs[m].items[kid].price
            };
            n++;
            if (n == rowspan) {
                kid++;
                if (kid > specs[m].items.length - 1) {
                    kid = 0;
                }
                n = 0;
            }
        }
    }

    var hh = '<input name="kw" type="hidden"  value="0"/>';
    for (var i = 0; i < newlen; i++) {

        hh += "<tr>";
        var ids = [];
        var titles = [];
        var virtuals = [];
        var specItemHiddenIds = [];
        var prices = [];
        for (var j = 0; j < len; j++) {
            hh += h[j][i].html;
            ids.push(h[j][i].id);
            titles.push(h[j][i].title);
            specItemHiddenIds.push(h[j][i].specItemHiddesId); // 建立specItem和sku之间的关系
            virtuals.push(h[j][i].virtual);
            prices.push(h[j][i].price);
        }
        ids = ids.join('_');
        titles = titles.join('+');
        specItemHiddenIds = specItemHiddenIds.join('_');

        var zitiprice = Number($("#zitiprice").val())
        for (var priceNum = 0; priceNum < prices.length; priceNum++) {
            zitiprice += Number(prices[priceNum]);
        }

        var tangshiprice = Number($("#tangshiprice").val())
        for (var priceNum = 0; priceNum < prices.length; priceNum++) {
            tangshiprice += Number(prices[priceNum]);
        }

        var waimaiprice = Number($("#waimaiprice").val())
        for (var priceNum = 0; priceNum < prices.length; priceNum++) {
            waimaiprice += Number(prices[priceNum]);
        }

        var tangshivipprice = Number($("#tangshivipprice").val())
        for (var priceNum = 0; priceNum < prices.length; priceNum++) {
            tangshivipprice += Number(prices[priceNum]);
        }

        var waimaivipprice = Number($("#waimaivipprice").val())
        for (var priceNum = 0; priceNum < prices.length; priceNum++) {
            waimaivipprice += Number(prices[priceNum]);
        }

        var zitivipprice = Number($("#zitivipprice").val())
        for (var priceNum = 0; priceNum < prices.length; priceNum++) {
            zitivipprice += Number(prices[priceNum]);
        }

        var marketPrice = Number($("#marketprice").val());
        for (var priceNum = 0; priceNum < prices.length; priceNum++) {
            marketPrice += Number(prices[priceNum]);
        }
        var vipprice = Number($("#vipprice").val());
        for (var priceNum = 0; priceNum < prices.length; priceNum++) {
            vipprice += Number(prices[priceNum]);
        }

        var val = {
            id: "",
            title: titles,
            stock: "",
            productprice: "",
            marketprice: marketPrice,
            vipprice: vipprice,
            zitiprice: zitiprice,
            tangshiprice: tangshiprice,
            waimaiprice: waimaiprice,
            tangshivipprice: tangshivipprice,
            waimaivipprice: waimaivipprice,
            zitivipprice: zitivipprice,
            weight: "",
            superiorcommission: "",
            headcommission: "",
            virtual: virtuals,
            specItemHiddenIds: specItemHiddenIds
        };
        if ($(".option_id_" + ids).length > 0) {
            val = {
                id: $(".option_id_" + ids + ":eq(0)").val(),
                title: titles,
                specItemHiddenIds: specItemHiddenIds,
                stock: $(".option_stock_" + ids + ":eq(0)").val(),
                productprice: $(".option_productprice_" + ids + ":eq(0)").val(),
                marketprice: marketPrice,
                //vipprice: $(".option_vipprice_" + ids + ":eq(0)").val(),
                vipprice: vipprice,
                zitiprice: zitiprice,
                tangshiprice: tangshiprice,
                waimaiprice: waimaiprice,
                tangshivipprice: tangshivipprice,
                waimaivipprice: waimaivipprice,
                zitivipprice: zitivipprice,
                weight: $(".option_weight_" + ids + ":eq(0)").val(),
                superiorcommission: $(".option_superiorcommission_" + ids + ":eq(0)").val(),
                headcommission: $(".option_headcommission_" + ids + ":eq(0)").val(),
                headtype: $(".option_headtype_" + ids + ":eq(0)").val(),
                superiortype: $(".option_superiortype_" + ids + ":eq(0)").val(),
                virtual: virtuals
            }
        }
        hh += '<td class="info">' + '<input name="option_stock_' + ids + '[]" type="number" min="0" class="form-control option_stock option_stock_' + ids + '" value="' + (val.stock == 'undefined' ? '' : val.stock) + '"/></td>';
        hh += '<input name="option_id_' + ids + '[]" type="hidden" class="form-control option_id option_id_' + ids + '" value="' + (val.id == 'undefined' ? '' : val.id) + '"/>';
        hh += '<input name="option_ids[]" type="hidden" class="form-control option_ids option_ids_' + ids + '" value="' + ids + '"/>';
        hh += '<input type="hidden" class="form-control option_title option_title_' + ids + '" value="' + (val.title == 'undefined' ? '' : val.title) + '"/></td>';
        hh += '<input type="hidden" class="form-control option_specItemHiddenId" value="' + (val.specItemHiddenIds == 'undefined' ? '' : val.specItemHiddenIds) + '"/></td>';
        /* hh += '<input name="option_virtual_' + ids + '[]"type="hidden" class="form-control option_title option_title_' + ids + '" value="' + (val.virtual == 'undefined' ? '': val.virtual) + '"/></td>'; */
        hh += '</td>';


        if (productType == 6) {
            if (isziti == 1) {
                hh += '<td class="success"><input readonly="readonly" name="option_marketprice_' + ids + '[]" type="number" min="0" class="form-control option_zitiprice option_marketprice_' + ids + '" value="' + (val.zitiprice == 'undefined' ? '' : val.zitiprice) + '"/></td>';
                hh += '<td class="warning"><input name="option_vipprice_' + ids + '[]" type="number" min="0" class="form-control option_zitivipprice option_vipprice_' + ids + '" " value="' + (val.zitivipprice == 'undefined' ? '' : val.zitivipprice) + '"/></td>';
            }
            if (istangshi == 1) {
                hh += '<td class="success"><input readonly="readonly" name="option_marketprice_' + ids + '[]" type="number" min="0" class="form-control option_tangshiprice option_marketprice_' + ids + '" value="' + (val.tangshiprice == 'undefined' ? '' : val.tangshiprice) + '"/></td>';
                hh += '<td class="warning"><input name="option_vipprice_' + ids + '[]" type="number" min="0" class="form-control option_tangshivipprice option_vipprice_' + ids + '" " value="' + (val.tangshivipprice == 'undefined' ? '' : val.tangshivipprice) + '"/></td>';
            }
            if (iswaimai == 1) {
                hh += '<td class="success"><input readonly="readonly" name="option_marketprice_' + ids + '[]" type="number" min="0" class="form-control option_waimaiprice option_marketprice_' + ids + '" value="' + (val.waimaiprice == 'undefined' ? '' : val.waimaiprice) + '"/></td>';
                hh += '<td class="warning"><input name="option_vipprice_' + ids + '[]" type="number" min="0" class="form-control option_waimaivipprice option_vipprice_' + ids + '" " value="' + (val.waimaivipprice == 'undefined' ? '' : val.waimaivipprice) + '"/></td>';
            }
        } else {
            hh += '<td class="success"><input readonly="readonly" name="option_marketprice_' + ids + '[]" type="number" min="0" class="form-control option_marketprice option_marketprice_' + ids + '" value="' + (val.marketprice == 'undefined' ? '' : val.marketprice) + '"/></td>';
            hh += '<td class="warning"><input name="option_productprice_' + ids + '[]" type="number" min="0" class="form-control option_productprice option_productprice_' + ids + '" " value="' + (val.productprice == 'undefined' ? '' : val.productprice) + '"/></td>';
            hh += '<td class="warning"><input name="option_vipprice_' + ids + '[]" type="number" min="0" class="form-control option_vipprice option_vipprice_' + ids + '" " value="' + (val.vipprice == 'undefined' ? '' : val.vipprice) + '"/></td>';
        }


        hh += '<td class="info"><input name="option_weight_' + ids + '[]" type="number" min="0" class="form-control option_weight option_weight_' + ids + '" " value="' + (val.weight == 'undefined' ? '' : val.weight) + '"/></td>';
        hh += '<td class="info" style="width:150px;"><div class=""><div class="input-group"><input name="option_headcommission_' + ids + '[]" type="number" min="0" class="form-control option_headcommission option_headcommission_' + ids + '" " value="' + (val.headcommission == 'undefined' ? '' : val.headcommission) + '"/><span class="input-group-addon" style="padding:0px;"><select  name="option_headtype_' + ids + '[]" type="text" class="option_headtype option_headtype_' + ids + '"  style="border-style:solid; border-color:#FFF"  ><option value="0"  >元</option><option value="1"  >%</option></select></span></div></div></td>';
        hh += '<td class="info" style="width:150px;"><div class=""><div class="input-group"><input name="option_superiorcommission_' + ids + '[]" type="number" min="0" class="form-control option_superiorcommission option_superiorcommission_' + ids + '" " value="' + (val.superiorcommission == 'undefined' ? '' : val.superiorcommission) + '"/><span class="input-group-addon" style="padding:0px;"><select  name="option_superiortype_' + ids + '[]" type="text" class="option_superiortype option_superiortype_' + ids + '"  style="border-style:solid; border-color:#FFF"  ><option value="0"  >元</option><option value="1">%</option></select></span></div></div></td>';
        hh += "</tr>";
    }
    html += hh;
    html += "</table>";
    $("#options").html(html);
}

function removeSpecItem(obj) {
    $(obj).parent().parent().parent().remove();
}

function checkoption() {
    var full = true;
    if ($("#hasoption").get(0).checked) {
        $(".spec_title").each(function (i) {
            if ($(this).val() == '' || $(this).val() == undefined) {
                layer.alert("请输入规格名称!", {icon: 5});
                full = false;
                return false;
            }
        });
        $(".spec_item_title").each(function (i) {
            if ($(this).val() == '' || $(this).val() == undefined) {
                layer.alert("请输入规格项名称!", {icon: 5});
                full = false;
                return false;
            }
        });
    }
    if (!full) {
        return false;
    }
    return full;
}

$(function () {
    $("#hasoption").click(function () {
        var obj = $(this);
        if (obj.get(0).checked) {
            $("#tboption").show();
        } else {
            $("#tboption").hide();
        }
    });
})

var optionchanged = false;

function saveProduct() {
    var specs = [];
    // 组装规格和规格属性
    if ($('.spec_item').length > 0) {
        $(".spec_item").each(function (i) {
            var specItems = [];
            var _this = $(this);
            $(_this.find(".spec_item_item")).each(function (i) {
                var _specItemItem = $(this);
                var specItem = {
                    id:_specItemItem.find('.spec_item_title').attr('data-index-oldId'),
                    title: _specItemItem.find('.spec_item_title').val(),
                    thumb: _specItemItem.find('.thumb').val(),
                    specItemHiddenId: _specItemItem.find('.spec_item_title').attr('data-index'),
                    price: _specItemItem.find('.spec_item_price').val()
                    /* thumb:_this.find */
                }
                specItems.push(specItem);
            })
            var spec = {
                title: _this.find(".spec_title").val(),
                specItemList: specItems
            };
            specs.push(spec); // 设置规格
        })
        /* console.info(specs); */
    }

    // 遍历sku，组装sku
    var skuList = [];
    $(".skuTable tbody tr").each(function () {
        var _this = $(this);
        var sku = {
            id: _this.find(".option_id").val(),
            title: _this.find(".option_title").val(),
            specItemHiddenId: _this.find(".option_specItemHiddenId").val(),
            productprice: _this.find(".option_productprice").val(),
            marketprice: _this.find(".option_marketprice").val(),
            vipprice: _this.find(".option_vipprice").val(),
            zitiprice: _this.find(".option_zitiprice").val(),
            tangshiprice: _this.find(".option_tangshiprice").val(),
            waimaiprice: _this.find(".option_waimaiprice").val(),
            tangshivipprice: _this.find(".option_tangshivipprice").val(),
            waimaivipprice: _this.find(".option_waimaivipprice").val(),
            zitivipprice: _this.find(".option_zitivipprice").val(),
            stock: _this.find(".option_stock").val(),
            weight: _this.find(".option_weight").val(),
            headcommission: _this.find(".option_headcommission").val(),
            headtype: _this.find(".option_headtype").val(),
            superiorcommission: _this.find(".option_superiorcommission").val(),
            superiortype: _this.find(".option_superiortype").val()

        }
        skuList.push(sku);
    })
    console.info(skuList);
    console.info(specs);

    var productType = $("#productType").val();
    var categoryType = $("#categoryType").val()
    if ($("#title").val() == '' || $("#title").val() == undefined) {
        layer.alert("请输入商品名称!", {icon: 5});
        return false;
    }

    if (!$("#pcate").val()) {
        layer.alert("请选择顶级分类!", {icon: 5});
        return false;
    }

    if (($("#liansuoid").val() == '' || $("#liansuoid").val() == undefined || $("#liansuoid").val() == 0) && ($("#teamId").val() == '' || $("#teamId").val() == undefined)) {
        layer.alert("请选择门店!", {icon: 5});
        return false;
    }

    if ($.trim($(':input[name="thumb"]').val()) == '') {
        layer.alert("请上传缩略图!", {icon: 5});
        return false;
    }

    var zitiprice = $("#zitiprice").val()
    var tangshiprice = $("#tangshiprice").val()
    var waimaiprice = $("#waimaiprice").val()
    var tangshivipprice = $("#tangshivipprice").val()
    var waimaivipprice = $("#waimaivipprice").val()
    var zitivipprice = $("#zitivipprice").val()


    var isziti = $("input[name='isziti']:checked").val();
    var istangshi = $("input[name='istangshi']:checked").val();
    var iswaimai = $("input[name='iswaimai']:checked").val();

    if ($("#total").val() == '' || $("#total").val() == undefined) {
        layer.alert("请输入商品库存!", {icon: 5});
        return false;
    }

    if (!$("#unit").val()) {
        layer.alert("请输入商品单位!", {icon: 5});
        return false;
    }

    if (productType != 6) {
        if ($("#marketprice").val() == '' || $("#marketprice").val() == undefined) {
            layer.alert("请输入商品现价!", {icon: 5});
            return false;
        }
        if ($("#costprice").val() == '' || $("#costprice").val() == undefined) {
            layer.alert("请输入商品成本价!", {icon: 5});
            return false;
        }
        if ($("#vipprice").val() == '' || $("#vipprice").val() == undefined) {
            layer.alert("请输入商品vip价!", {icon: 5});
            return false;
        }
    } else {
        if (isziti == 1) {
            if (zitiprice == '' || zitiprice == undefined) {
                layer.alert("请输入自提价!", {icon: 5});
                return false;
            }
            if (zitivipprice == '' || zitivipprice == undefined) {
                layer.alert("请输入自提vip价!", {icon: 5});
                return false;
            }
        }
        if (istangshi == 1) {
            if (tangshiprice == '' || tangshiprice == undefined) {
                layer.alert("请输入堂食价!", {icon: 5});
                return false;
            }
            if (tangshivipprice == '' || tangshivipprice == undefined) {
                layer.alert("请输入堂食vip价!", {icon: 5});
                return false;
            }
        }
        if (iswaimai == 1) {
            if (waimaiprice == '' || waimaiprice == undefined) {
                layer.alert("请输入外卖现价!", {icon: 5});
                return false;
            }
            if (waimaivipprice == '' || waimaivipprice == undefined) {
                layer.alert("请输入外卖vip价!", {icon: 5});
                return false;
            }
        }
    }

    var full = true;
    full = checkoption();
    if (!full) {
        return false;
    }
    if (optionchanged) {
        layer.alert("规格数据有变动，请重新点击 [刷新规格项目表] 按钮!", {icon: 5});
        return false;
    }
    var displayorder = $("#displayorder").val();
    if (displayorder > 2147483647) {
        layer.msg("排序值过大");
        return;
    }
    var title = $("#title").val();
    var shortTitle = $("#shortTitle").val();
    var goodscode = $("#goodscode").val();
    var specTitle = $("#specTitle").val();
    var pinyinkeyword = $("#pinyinkeyword").val();
    var pcate = $("#pcate").val();
    var ccate = $("#ccate").val();
    var supplierId = $("#supplierId").val();
    var liansuoid = $("#teamId").val() != null && $("#teamId").val() != '' ? $("#teamId").val() : $("#liansuoid").val();
    var unit = $("#unit").val();
    var isrecommand = $("input[name='isrecommand']:checked").val();
    var isTeamBuy = $("input[name='isTeamBuy']:checked").val();
    var isKuaidi = $("input[name='isKuaidi']:checked").val();
    var isnew = $("input[name='isnew']:checked").val();
    var ishot = $("input[name='ishot']:checked").val();
    var isdiscount = $("input[name='isdiscount']:checked").val();
    var istime = $("input[name='istime']:checked").val();
    var ismiaosha = $("input[name='ismiaosha']:checked").val();
    var islimited = $("input[name='islimited']:checked").val();

    var iszhicai = $("input[name='iszhicai']:checked").val();
    var ismao = $("input[name='ismao']:checked").val();
    var isfanchang = $("input[name='isfanchang']:checked").val();
    /* var isgerida = $("input[name='isgerida']:checked").val(); */
    var isfashi = $("input[name='isfashi']:checked").val();
    var iszhutihuakuang = $("input[name='iszhutihuakuang']:checked").val();
    var manudate = $("#manudate").val();
    var guarantday = $("#guarantday").val();

    var selfvalue = $("#selfvalue").val();
    var timestart = $("#timestart").val();
    var timeend = $("#timeend").val();
    if (istime == 0 && (timestart == '' || timestart == undefined || timeend == '' || timeend == undefined)) {
        layer.msg("请输入商品限卖时间", {icon: 5});
        return false;
    }
    var thumb = $("#thumb").val();
    var thumbSquare = $("#thumbSquare").val();
    var thumbUrlBak = $("#thumbUrlBak").val();
    var videourl = $("#videourl").val();
    var thumbUrl = $("#thumbUrl").val();
    var marketprice = $("#marketprice").val();

    var startLimit = $("#startLimit").val();

    var costprice = $("#costprice").val();
    var vipprice = $("#vipprice").val();
    var weight = $("#weight").val();
    var total = $("#total").val();
    var maxbuy = $("#maxbuy").val();
    var usermaxbuy = $("#usermaxbuy").val();

    var sales = $("#sales").val();
    var viewcount = $("#viewcount").val();
    var credit = $("#credit").val();
    var status = $('input[name="status"]:checked').val();
    if (status == 2) {
        var upStartTime = $("#upStartTime").val();
        var upEndTime = $("#upEndTime").val();
    }
    var isgongyi = $('input[name="isgongyi"]:checked').val();
    if (isgongyi == 1) {
        var gongyiprice = $("#gongyiprice").val();
    }
    var areas = $("#selectedareas").val();
    var showsupply = $('input[name="showsupply"]:checked').val();
    var uncancelable = $('input[name="uncancelable"]:checked').val();
    //var description = UE.getEditor('content').getContent();
    var tihuoday = $("#tihuoday").val();
    // var freeShipping = $('input[name="free_shipping"]:checked').val();
    var sendprice = $("#sendprice").val(); // 独立邮费
    var dispatchid = $("#dispatchid").val(); // 邮费模板

    var isFxCommission = 0; //是否开启门店佣金
    if ($('#is_fx_commission').is(':checked')) {
        isFxCommission = 1;
    }
    var headcommission = $("#headcommission").val();  //门店佣金设置
    var headtype = $("#headtype").val();
    var clerkercommission = $("#clerkercommission").val();  //门店佣金设置
    var clerkertype = $("#clerkertype").val();
    var superiorcommission = $("#superiorcommission").val();
    var superiortype = $("#superiortype").val();
    var proddes = $("#proddes").val();
    var usercommission = $("#usercommission").val();
    var usertype = $("#usertype").val();
    var superusercommission = $("#superusercommission").val();
    var superusertype = $("#superusertype").val();
    var isSpellgroup = $("input[name='isSpellgroup']:checked").val();
    var spellgroupnum = $("#spellgroupnum").val();
    var ispresell = $("input[name='ispresell']:checked").val();
    var discountStatus = $("input[name='discountStatus']:checked").val();
    var discount = $("#discount").val();
    var productprice = $("#waimaiproductprice").val()
    var id = $("#id").val()
    var  consumptionIntegral = $("#consumptionIntegral").val()
    var data = {
        "id": id,
        "displayorder": displayorder,
        "goodscode": goodscode,
        "specTitle": specTitle,
        "pinyinkeyword": pinyinkeyword,
        "pcate": pcate,
        "ccate": ccate,
        "supplierId": supplierId,
        "isrecommand": isrecommand,
        "title": title,
        "shortTitle": shortTitle,
        "unit": unit,
        "selfvalue": selfvalue,
        "timestart": timestart,
        "timeend": timeend,
        "thumb": thumb,
        "thumbSquare": thumbSquare,
        "thumbUrlBak": thumbUrlBak,
        "videourl": videourl,
        "thumbUrl": thumbUrl,
        "marketprice": marketprice,
        "startLimit": startLimit,
        "productprice": productprice,
        "costprice": costprice,
        "vipprice": vipprice,
        "weight": weight,
        "total": total,
        "maxbuy": maxbuy,
        "usermaxbuy": usermaxbuy,
        "sales": sales,
        "status": status,
        "upStartTime": upStartTime,
        "upEndTime": upEndTime,
        "isgongyi": isgongyi,
        "viewcount": viewcount,
        "gongyiprice": gongyiprice,
        "showsupply": showsupply,
        "uncancelable": uncancelable,
        "areas": areas,
        //"description": description,
        //"freeShipping": freeShipping,
        "sendprice": sendprice,
        "dispatchid": dispatchid,
        "isFxCommission": isFxCommission,
        "headcommission": headcommission,
        "headtype": headtype,
        "clerkercommission": clerkercommission,
        "clerkertype": clerkertype,
        "superiorcommission": superiorcommission,
        "superiortype": superiortype,
        "tihuoday": tihuoday,
        "guarantday": guarantday,
        "manudate": manudate,
        "proddes": proddes,
        "credit": credit,
        "liansuoid": liansuoid,
        "usertype": usertype,
        "usercommission": usercommission,
        "superusertype": superusertype,
        "superusercommission": superusercommission,
        "isSpellgroup": isSpellgroup,
        "spellgroupnum": spellgroupnum,
        "ispresell": ispresell,
        "productType": productType,
        "zitiprice": zitiprice,
        "tangshiprice": tangshiprice,
        "waimaiprice": waimaiprice,
        "tangshivipprice": tangshivipprice,
        "waimaivipprice": waimaivipprice,
        "zitivipprice": zitivipprice,
        "discountStatus": discountStatus,
        "discount": discount,
        "categoryType": categoryType,
        "consumptionIntegral":consumptionIntegral
    };

    data.specList = specs;
    data.skuList = skuList;
    if (isziti == 1) {
        data.isziti = 1
    } else {
        data.isziti = 0
    }
    ;
    if (istangshi == 1) {
        data.istangshi = 1
    } else {
        data.istangshi = 0
    }
    ;
    if (iswaimai == 1) {
        data.iswaimai = 1
    } else {
        data.iswaimai = 0
    }
    ;
    if (isrecommand == 1) data.isrecommand = 1;
    if (isnew == 1) data.isnew = 1;
    if (isTeamBuy == 1) data.isTeamBuy = 1;
    if (ishot == 1) data.ishot = 1;
    if (isKuaidi == 1) data.isKuaidi = 1;
    if (isdiscount == 1) data.isdiscount = 1;
    if (ismiaosha == 1) data.ismiaosha = 1;
    if (islimited == 1) data.islimited = 1;
    if (istime == 1) {
        data.istime = 1
    } else {
        data.istime = 0
    }
    ;
    if (iszhicai == 1) data.iszhicai = 1;
    if (ismao == 1) data.ismao = 1;
    if (isfanchang == 1) data.isfanchang = 1;
    /* if (isgerida == 1) data.isgerida=1; */
    if (isfashi == 1) data.isfashi = 1;
    if (iszhutihuakuang == 1) data.iszhutihuakuang = 1;

    var hasoption = $("input[name='hasoption']:checked").val();
    var secondSpec = 0;
    if (hasoption == 1) data.hasoption = 1;
    if (secondSpec == 1) data.hasoptionsbuy = 1;

    $.ajax({
        url: '/product/centre/add',
        contentType: "application/json",
        dataType: "json",
        type: 'POST',
        data: JSON.stringify(data),
        success: function (result) {
            if (result.code == 0) {
                $("#productid").val(result.msg);
                layer.alert("保存成功", {icon: 6});
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
            } else {
                if (result.msg == '' || result.msg == null) {
                    layer.alert("保存失败，请联系管理员", {icon: 5});
                } else {
                    layer.alert(result.msg, {icon: 5});
                }

            }
        }
    })
}

// ----------------------------------------------------------------套餐----------------------------------------------------------------------------------------------------


function packageToCategoryOne() {
    // iframe层
    layer.open({
        id: 'group_add',
        type: 2,
        title: '选择顶级分类',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['90%', '90%'],
        content: '/category/manage/toCategory?idDom=packagePcate&nameDom=packagePcateName&singleSelect=1&callback=packagePcateCallback&count=1' // iframe的url
    });
}

function packageToCategoryTwo() {
    var parentid = $("#packagePcate").val();
    if (!parentid) {
        layer.msg("请选择顶级分类");
        return;
    }
    // iframe层
    layer.open({
        id: 'group_add',
        type: 2,
        title: '选择下级分类',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['90%', '90%'],
        content: '/category/manage/toCategory?idDom=packageCcate&nameDom=packageCcateName&singleSelect=1&callback=packagePcateCallback&count=2&parentid=' + parentid // iframe的url
    });
}

function packagePcateCallback(obj) {
    $("#" + obj.nameDom).val(obj.nameStrs);
    $("#" + obj.idDom).val(obj.idStrs);
    if (obj.count == 1) {
        $("#packageCcate").val("");
        $("#packageCcateName").val("");
    }
}

function packageCategoryCloseClick(event) {
    if (event == 'one') { // 一级分类清空
        $("#packagePcateName").val('')
        $("#packagePcate").val('')
        $("#packageCcateName").val('')
        $("#packageCcate").val('')
    } else { // 二级分类清空
        $("#packageCcateName").val('')
        $("#packageCcate").val('')

    }
}


function radioIsCheckedPackage() {
    if ($("#istime2Package").is(':checked')) {
        $('#istimePackage').show();
    } else {
        $('#istimePackage').hide();
    }
}

function iszitiPackageChange() {
    var isziti = $("input[name='iszitiPackage']:checked").val();
    if (isziti == 1) {
        $("#zitiPackage").css("display", "block");
    } else {
        $("#zitiPackage").css("display", "none");
        $("#zitipricePackage").val("")
        $("#zitivippricePackage").val("")
    }
}

function istangshiPackageChange() {
    var istangshi = $("input[name='istangshiPackage']:checked").val();
    if (istangshi == 1) {
        $("#tangshiPackage").css("display", "block");
        $("#discount1Package").css("display", "block");
        $("#discount2Package").css("display", "block");
    } else {
        $("#discount1Package").css("display", "none");
        $("#discount2Package").css("display", "none");
        $("#tangshiPackage").css("display", "none");
        $("#tangshipricePackage").val("")
        $("#tangshivippricePackage").val("")
        $("input[name='discountStatusPackage']:checked").prop("checked", false);
        $('input:radio[name=discountStatusPackage]')[1].checked = true;
        $("#discountPackage").val("")
    }
}

function iswaimaiPackageChange() {
    var iswaimai = $("input[name='iswaimaiPackage']:checked").val();
    if (iswaimai == 1) {
        $("#waimaiPackage").css("display", "block");
    } else {
        $("#waimaiPackage").css("display", "none");
        $("#waimaiproductpricePackage").val("")
        $("#waimaipricePackage").val("")
        $("#waimaivippricePackage").val("")
    }
}

function setCol(cls) {
    $("." + cls).val($("." + cls + "_all").val());
}

function saveProductPackage() {
    var categoryType = $("#categoryType").val()
    var productType = $("#productType").val();

    if ($("#packageTitle").val() == '' || $("#packageTitle").val() == undefined) {
        layer.alert("请输入套餐名称!", {icon: 5});
        return false;
    }

    if (($("#liansuoidPackage").val() == '' || $("#liansuoidPackage").val() == undefined || $("#liansuoidPackage").val() == 0) && ($("#teamId").val() == '' || $("#teamId").val() == undefined)) {
        layer.alert("请选择门店!", {icon: 5});
        return false;
    }

    if ($.trim($(':input[name="thumbPackage"]').val()) == '') {
        layer.alert("请上传缩略图!", {icon: 5});
        return false;
    }

    var packageSkuList = [];
    if (this.packageNum > 0) {
        var bol = false;
        for (var i = 1; i <= this.packageNum; i++) {
            if (this.packageSkuData[i] && this.packageSkuData[i] != null) {
                bol = true
                packageSkuList.push(this.packageSkuData[i]);
            }
        }
        if (!bol) {
            layer.alert("请添加单品!", {icon: 5});
            return false;
        }
    } else {
        layer.alert("请添加单品!", {icon: 5});
        return false;
    }

    var zitiprice = $("#zitipricePackage").val()
    var tangshiprice = $("#tangshipricePackage").val()
    var waimaiprice = $("#waimaipricePackage").val()
    var tangshivipprice = $("#tangshivippricePackage").val()
    var waimaivipprice = $("#waimaivippricePackage").val()
    var zitivipprice = $("#zitivippricePackage").val()

    var isziti = $("input[name='iszitiPackage']:checked").val();
    var istangshi = $("input[name='istangshiPackage']:checked").val();
    var iswaimai = $("input[name='iswaimaiPackage']:checked").val();

    if ($("#packageTotal").val() == '' || $("#packageTotal").val() == undefined) {
        layer.alert("请输入商品库存!", {icon: 5});
        return false;
    }

    if (!$("#packageUnit").val()) {
        layer.alert("请输入商品单位!", {icon: 5});
        return false;
    }

    if (productType != 6) {
    } else {
        if (isziti == 1) {
            if (zitiprice == '' || zitiprice == undefined) {
                layer.alert("请输入自提价!", {icon: 5});
                return false;
            }
            if (zitivipprice == '' || zitivipprice == undefined) {
                layer.alert("请输入自提vip价!", {icon: 5});
                return false;
            }
        }
        if (istangshi == 1) {
            if (tangshiprice == '' || tangshiprice == undefined) {
                layer.alert("请输入堂食价!", {icon: 5});
                return false;
            }
            if (tangshivipprice == '' || tangshivipprice == undefined) {
                layer.alert("请输入堂食vip价!", {icon: 5});
                return false;
            }
        }
        if (iswaimai == 1) {
            if (waimaiprice == '' || waimaiprice == undefined) {
                layer.alert("请输入外卖现价!", {icon: 5});
                return false;
            }
            if (waimaivipprice == '' || waimaivipprice == undefined) {
                layer.alert("请输入外卖vip价!", {icon: 5});
                return false;
            }
        }
    }

    var displayorder = $("#displayorderPackage").val();
    if (displayorder > 2147483647) {
        layer.msg("排序值过大");
        return;
    }
    var title = $("#packageTitle").val();
    var pcate = $("#packagePcate").val();
    var ccate = $("#packageCcate").val();
    var liansuoid = $("#teamId").val() != null && $("#teamId").val() != '' ? $("#teamId").val() : $("#liansuoidPackage").val();
    var unit = $("#packageUnit").val();
    var istime = $("input[name='istimePackage']:checked").val();
    var timestart = $("#timestartPackage").val();
    var timeend = $("#timeendPackage").val();
    if (istime == 0 && (timestart == '' || timestart == undefined || timeend == '' || timeend == undefined)) {
        layer.msg("请输入商品限卖时间", {icon: 5});
        return false;
    }
    var thumb = $("#thumbPackage").val();
    var total = $("#packageTotal").val();
    var discountStatus = $("input[name='discountStatusPackage']:checked").val();
    var discount = $("#discountPackage").val();
    var productprice = $("#waimaiproductpricePackage").val()
    var id = $("#id").val()
    var shortTitle = $("#shortTitlePackage").val()
    var consumptionIntegralPackage = $("#consumptionIntegralPackage").val()
    var data = {
        "id": id,
        "displayorder": displayorder,
        "pcate": pcate,
        "ccate": ccate,
        "title": title,
        "shortTitle": shortTitle,
        "unit": unit,
        "timestart": timestart,
        "timeend": timeend,
        "thumb": thumb,
        "productprice": productprice,
        "total": total,
        "liansuoid": liansuoid,
        "productType": productType,
        "zitiprice": zitiprice,
        "tangshiprice": tangshiprice,
        "waimaiprice": waimaiprice,
        "tangshivipprice": tangshivipprice,
        "waimaivipprice": waimaivipprice,
        "zitivipprice": zitivipprice,
        "discountStatus": discountStatus,
        "discount": discount,
        "productPackageFlag": 1,
        "categoryType": categoryType,
        "consumptionIntegralPackage":consumptionIntegralPackage
    };
    if (isziti == 1) {
        data.isziti = 1
    } else {
        data.isziti = 0
    }
    ;
    if (istangshi == 1) {
        data.istangshi = 1
    } else {
        data.istangshi = 0
    }
    ;
    if (iswaimai == 1) {
        data.iswaimai = 1
    } else {
        data.iswaimai = 0
    }
    ;
    if (discountStatus == 1) data.isdiscount = 1;
    if (istime == 1) data.istime = 1;

    data.packageSkuList = packageSkuList;

    $.ajax({
        url: '/product/centre/add',
        contentType: "application/json",
        dataType: "json",
        type: 'POST',
        data: JSON.stringify(data),
        success: function (result) {
            if (result.code == 0) {
                $("#productid").val(result.msg);
                layer.alert("保存成功", {icon: 6});
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
            } else {
                if (result.msg == '' || result.msg == null) {
                    layer.alert("保存失败，请联系管理员", {icon: 5});
                } else {
                    layer.alert(result.msg, {icon: 5});
                }

            }
        }
    })
}

var packageNum = 0;

function addPackage() {
    packageNum++;
    var html = "<div class='col-sm-6 col-md-4' id='packageDiv" + packageNum + "'>\n" +
        "        <input id='packageNum' type='hidden' value='" + packageNum + "'>\n" +
        "        <div class='thumbnail' style='width: 360px;height: 500px;'>\n" +
        "            <img style='border:1px solid #ddd;padding:5px;min-width:95%;min-height:70%;max-width:95%;max-height:70%;'\n" +
        "                 id='packageThumb" + packageNum + "' src='...'>\n" +
        "                <div class='caption'>\n" +
        "                    <h3 id='productName" + packageNum + "'>单品名称</h3>\n" +
        "                    <p>规格:<em id='spec" + packageNum + "'></em></p>\n" +
        "                    <p>库存:<em id='inventory" + packageNum + "'></em></p>\n" +
        "                    <p><a onclick='deleteGoods(" + packageNum + ")' href='###' class='btn btn-primary' role='button'>删除</a> <a onclick='selectGoods(" + packageNum + ")' href='###'\n" +
        "                                                                                       class='btn btn-default'\n" +
        "                                                                                       role='button'>选择商品</a></p>\n" +
        "                </div>\n" +
        "        </div>\n" +
        "    </input>";
    $("#packageEnd").before(html);
}

function deleteGoods(index) {
    $("#packageDiv" + index).remove();
    this.packageSkuData[index + ""] = null
}

function selectGoods(index) {
    // iframe层
    layer.open({
        id: 'package_add',
        type: 2,
        title: '选择单品',
        maxmin: true,
        shadeClose: false, // 点击遮罩关闭层
        area: ['90%', '90%'],
        content: '/product/restaurant/toChooseProduct?packageNum=' + index // iframe的url
    });
}

//套餐商品及规格
var packageSkuData = [];

function selectProductCallBack(productData, skuData, packageNum) {
    // //给商品选择框赋值
    $("#packageThumb" + packageNum).attr("src", productData.thumb);
    $("#productName" + packageNum).html(productData.title);
    if (skuData) {
        $("#spec" + packageNum).html(skuData.title);
        $("#inventory" + packageNum).html(skuData.stock);
    } else {
        $("#spec" + packageNum).html("无");
        $("#inventory" + packageNum).html(productData.total);
    }
    //存储选择的套餐内商品
    this.packageSkuData[packageNum + ""] = {
        refProductCentreId: productData.id,
        centreId: productData.centreId,
        skuId: skuData ? skuData.id : null,
        title: skuData ? skuData.title : null,
        thumb: skuData ? skuData.thumb : null,
        specs: skuData ? skuData.specs : null,
        stock: skuData ? skuData.stock : null,
    }
}

function removeSpec(specid) {
    if (confirm('确认要删除此规格?')) {
        $("#spec_" + specid).remove();
        optionchanged = true;
    }
    //specCountNum--;
}